<template>
	<uv-popup ref="popup" :round="10" @close="closeDialog">
		<view style="width: 80vw;padding:20rpx;">
			<view class="popup-title" style="margin-bottom:20rpx;font-size: 32rpx;
				font-weight: 700;">
				发现新版本
			</view>
			<view style="margin-bottom:20rpx;max-height:400rpx;overflow-y: auto;white-space: pre-line;">
				{{updataInfo.description}}
			</view>
			<view v-if="downloading">
				<cl-progress :value="downLoadPercent" :show-text="false"
					:color="['#F56C6C', '#E6A23C', '#67c23a']"></cl-progress>
			</view>
			<view v-if="downloadSuccess&&!downloading">
				<cl-button type="primary" fill @click="installPackage()">立即安装</cl-button>
			</view>
			<view v-if="!downloadSuccess&&!downloading">
				<cl-button type="primary" fill @click="updataApp()">立即更新</cl-button>
			</view>
		<!-- 	<cl-checkbox :size="34" v-model="userNotRemind" round size="20">
				<view class="agree-btn">
					七天内不再提醒
				</view>
			</cl-checkbox> -->
			<!-- 确认是否重启弹框 -->
			<cl-confirm ref="Confirm"></cl-confirm>
		</view>
	</uv-popup>
</template>
<script lang="ts" setup>
	import { ref, onMounted } from "vue";
	import { useCool, useApp,useVersion } from "/@/cool";
	import { useUi } from "/$/cool-ui";
	const app = useApp();
	const version=useVersion()
	const {  storage } = useCool();
	const ui = useUi();
	const Confirm = ref<ClConfirm.Ref>();
	const popup = ref()
	// 下载下载状态
	const downloading = ref("");
	// 是否下载成功
	const downloadSuccess = ref(false);
	// 下载进度
	const downLoadPercent = ref(0);
	// 已下载大小
	const downloadedSize = ref(0);
	// app总大小
	const packageFileSize = ref(0);
	// wgt是否安装中
	const wgtInstalling = ref(false);
	//  wgt是否安装完成
	const wgtInstalled = ref(false);
	// 要安装的本地包地址
	const tempFilePath = ref(false);
	//  wgt之前的安装的本地包地址
	const installForBeforeFilePath = ref(null);
	//  创建的下载任务
	const downloadTask = ref(null);
	//  用户上次拒绝的时间
	const userLastRefuseTime = ref(storage.get('userLastRefuseTime'));
	//  用户是否短期内不更新
	const userNotRemind = ref(false);
	// 后台返回的数据
	const updataInfo = ref({})
	onMounted(() => {
		init()
	});
	// 版本对比
	function compare(v1 = '0', v2 = '0') {
		v1 = String(v1).split('.') + ''
		v2 = String(v2).split('.') + ''
		const minVersionLens = Math.min(v1.length, v2.length);
		let result = 0;
		for (let i = 0; i < minVersionLens; i++) {
			const curV1 = Number(v1[i])
			const curV2 = Number(v2[i])

			if (curV1 > curV2) {
				result = 1
				break;
			} else if (curV1 < curV2) {
				result = -1
				break;
			}
		}

		if (result === 0 && (v1.length !== v2.length)) {
			const v1BiggerThenv2 = v1.length > v2.length;
			const maxLensVersion = v1BiggerThenv2 ? v1 : v2;
			for (let i = minVersionLens; i < maxLensVersion.length; i++) {
				const curVersion = Number(maxLensVersion[i])
				if (curVersion > 0) {
					v1BiggerThenv2 ? result = 1 : result = -1
					break;
				}
			}
		}

		return result;
	}
	// 初始化
	async function init() {
		// #ifdef APP
		// // 如果在用户上次拒绝的时间存在
		if (userLastRefuseTime.value) {
			// 目标时间戳
			let targetTime = userLastRefuseTime.value + 7 * 24 * 60 * 60 * 1000;
			// 现在时间戳
			let nowTime = (new Date).getTime();
			// 如果目标时间戳大于现在时间戳
			if (targetTime > nowTime) {
				// 并阻止执行   
				return;
			} else {
				// 清除拒绝时间
				storage.remove('userLastRefuseTime');
			}
		}
		version.check().then(res=>{
			if(res){
				// console.log(res,"resss")
				updataInfo.value=res
				const appDownLoadTempFilePath = storage.get('appDownLoadTempFilePath');
				if (appDownLoadTempFilePath && compare(updataInfo.value.version, storage.get(
					'appDownLoadTempFilePathVersion')) == 0) {
					tempFilePath.value = appDownLoadTempFilePath;
					downloadSuccess.value = true;
					installForBeforeFilePath.value = appDownLoadTempFilePath;
				} else {
					storage.remove('appDownLoadTempFilePath');
					storage.remove('appDownLoadTempFilePathVersion');
				}
				popup.value.open()
				// updataApp()
			}
			
		})
		// #endif
	}
	// 应用更新
	async function updataApp() {
		// 热更新
		if (updataInfo.value?.hotUpdate == 1) {
			await downloadPackage()
		} else {
			plus.runtime.openURL(updataInfo.value?.url);
		}
		// installPackage()
	}
	// 下载app
	function downloadPackage() {
		return new Promise((resolve) => {

			if (!downloadTask.value) {
				downloading.value = true;
				//下载包
				downloadTask.value = plus.downloader.createDownload(updataInfo.value.url, {}, (download, status) => {
					if (status == 200) {
						downloadSuccess.value = true;
						tempFilePath.value = download.filename;
						storage.set('appDownLoadTempFilePathVersion', updataInfo.value.version)
						storage.set('appDownLoadTempFilePath', tempFilePath.value);
					}
					// 清空下载进度
					downLoadPercent.value = 0;
					downloadedSize.value = 0;
					packageFileSize.value = 0;
					downloadTask.value = null;
				});

				downloadTask.value.start();

				downloadTask.value.addEventListener("statechanged", (task : any) => {
					switch (task.state) {
						case 3:
							// 更新下载进度
							downLoadPercent.value = parseInt((task.downloadedSize / task.totalSize * 100) + '');
							downloadedSize.value = (task.downloadedSize / Math.pow(1024, 2)).toFixed(2);
							packageFileSize.value = (task.totalSize / Math.pow(1024, 2)).toFixed(2);
							if (downLoadPercent.value == 100) {
								downloading.value = false
								console.log(downLoadPercent.value)
								resolve(true)
							}
							break;
					}
				});
			}
		})
	}
	// 安装app
	function installPackage() {
		// wgt资源包安装
		if (updataInfo.value.hotUpdate == 1) {
			wgtInstalling.value = true;
		}
		plus.runtime.install(tempFilePath.value, {
			force: true
		}, () => {
			wgtInstalling.value = false;
			wgtInstalled.value = true;
			console.log("anzhuan")
			restart()
		}, err => {
			downloadSuccess.value = false;
			// 如果是安装之前的包，安装失败后删除之前的包
			if (installForBeforeFilePath.value) {
				deleteSavedFile(installForBeforeFilePath.value)
				installForBeforeFilePath.value = '';
			}
			ui.showToast(err.message);
		})
	}

	// 删除保存的文件
	function deleteSavedFile(tempFilePath : string) {
		storage.remove('appDownLoadTempFilePath')
		storage.remove({
			tempFilePath
		})
	}

	// 保存文件
	function saveFile(tempFilePath : string) {
		return new Promise((resolve) => {
			uni.saveFile({
				tempFilePath,
				success() {
					storage.set('appDownLoadTempFilePath', tempFilePath)
				},
				complete() {
					resolve(true)
				}
			})
		})
	}
	// 重启应用
	function restart() {
		Confirm.value?.open({
			title: "提示",
			message: "需要重启体验最新功能",
			showCancelButton: false,
			callback(action : any) {
				switch (action) {
					case "confirm":
						wgtInstalled.value = false;
						//更新完重启app
						plus.runtime.restart();
						deleteSavedFile(installForBeforeFilePath.value)
						break;
					case "cancel":
						ui.showToast("已取消");
						break;

					case "close":
						ui.showToast("已关闭");
						break;
				}
			}
		});
	}
	// 更新用户拒绝时间
	function updataUserRefuseTime() {
		// 存储用户暂不升级的时间戳
		userLastRefuseTime.value = (new Date).getTime();
		storage.set('userLastRefuseTime', userLastRefuseTime.value);
	}
	// 关闭更新框
	function closeDialog(res : { show : any; }) {
		console.log(res)
		// if(!res.show){
			console.log(123123)
		if (downloading.value) {
			Confirm.value?.open({
				title: "提示",
				message: "是否取消下载",
				callback(action : any) {
					switch (action) {
						case "confirm":
							downloadTask.value && downloadTask.value.abort();
							popup.value.close()
							break;

						case "cancel":
							ui.showToast("已取消");
							break;

						case "close":
							ui.showToast("已关闭");
							break;
					}
				}
			});
		} else {
			popup.value.close()
			console.log(userNotRemind.value)
			// 如果用户短期内不更新
			if (userNotRemind.value) {
				updataUserRefuseTime();
			}
		}
		if (downloadSuccess.value) {
			// 包已经下载完毕，稍后安装，将包保存在本地
			saveFile(tempFilePath.value)
		}
		// }

	}
</script>

<style lang="scss" scoped>
	.flex-center {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.margin-auto {
		margin: auto
	}

	.progress {
		padding-bottom: 20rpx;
	}

	.agree-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #999999;
		letter-spacing: 1rpx;
		font-size: 24rpx;

		text {
			color: $cl-color-primary;
			padding: 0 10rpx;
		}
	}
</style>